<?php

namespace Modules\Activity\Entities\Lottery;

use Illuminate\Database\Eloquent\Builder;

use Modules\Core\Entities\BaseEntity as Model;

use ThrowException;

class Record extends Model
{
    // 代付订单

    protected $guarded = [];
    protected $table = 'lottery_records';

    static public $resourceName = '活动记录';

    public function scopeType($query, $type)
    {
        return $query->whereHas('activity', function ($q) use ($type) {
            return $q->type($type);
        });
    }

    public function scopeStatus($query, $status) 
    {
        return $query->whereHas('activity', function ($q) use ($status) {
            return $q->status($status);
        });
    }

    public function scopeLucky($query) 
    {
        return $query->where('is_lucky_user', 1);
    }

    //  所属活动
    public function activity()
    {
        return $this->belongsTo('\Modules\Activity\Entities\Lottery\Activity');
    }

    // 所有抽奖码
    public function tickets()
    {
        return $this->hasMany('\Modules\Activity\Entities\Lottery\Ticket', 'activity_record_id');
    }


    // 抽奖票
    public function invitees()
    {
        return $this->hasMany('\Modules\Activity\Entities\Lottery\InviteeRecord', 'activity_record_id');
    }

    // 所属用户
    public function user()
    {
        return $this->belongsTo('\Modules\User\Entities\User', 'user_id');
    }

    static public function createWith($activity, $user, $options = []) 
    {
        $info = [
            'user_id' => $user->id,
            'session' => $activity->current_session,
            'activity_id' => $activity->id,
            'order_id' => @$options['order']->id,
            'join_code' => @$options['join_code']
        ];

        return self::create($info);
    }

}
